package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(String phone, HttpSession session) {
        //校验手机号是否合法
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号格式错误");
        }
        //使用hutool工具包生成验证码
        String code = RandomUtil.randomNumbers(6);

        //保存验证码到redis
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY + phone, code, CACHE_NULL_TTL, TimeUnit.MINUTES);
        //发送验证码
        log.info("验证码是{}", code);

        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //虽然在在sendCode接口中已经校验了手机号，但这是又一个请求，防止更改手机号
        if (RegexUtils.isPhoneInvalid(loginForm.getPhone())) {
            return Result.fail("手机号格式错误");
        }
        //校验验证码
        String cacheCode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + loginForm.getPhone());
        String code = loginForm.getCode();
        if (code == null || !cacheCode.equals(code)) {
            return Result.fail("验证码错误");
        }
        //验证码一致，查询用户
        //用户若不存在，添加到表中
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, loginForm.getPhone());
        User user = getOne(queryWrapper);
        if (user == null) {
            user = new User();
            user.setPhone(loginForm.getPhone());
            user.setNickName("user_" + RandomUtil.randomString(10));
            save(user);
        }
        String token = UUID.randomUUID().toString();
        //UserDTO userDTO=BeanUtils.copyProperties(user, UserDTO.class);

        //使用hutoll包中的属性拷贝
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        //beanToMap是将java对象转换为map集合
        Map<String, Object> map = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                //CopyOptions.create().setFieldValueEditor((filedName, filedValue) -> filedValue.toString())
                //这是自定义的拷贝规则，将所有属性值转换为字符串
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((filedName, filedValue) -> filedValue.toString())
        );


        stringRedisTemplate.opsForHash().putAll(LOGIN_USER_KEY + token, map);

        //设置token有效期
        stringRedisTemplate.expire(LOGIN_USER_KEY + token, 30, TimeUnit.MINUTES);
        return Result.ok(token);
    }

    @Override
    public Result sign() {
        //获取当前登录用户
        Long userId = UserHolder.getUser().getId();
        LocalDateTime now = LocalDateTime.now();
        String format = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        log.info("format:{}", format);
        //获取今天是本月的第几天
        int dayOfMonth = now.getDayOfMonth();
        String key = "sign:" + userId + format;
        stringRedisTemplate.opsForValue().setBit(key, dayOfMonth - 1, true);
        return Result.ok();
    }

    @Override
    public Result signCount() {
        //获取当前登录用户
        Long userId = UserHolder.getUser().getId();
        LocalDateTime now = LocalDateTime.now();
        String format = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        log.info("format:{}", format);
        //获取今天是本月的第几天
        int dayOfMonth = now.getDayOfMonth();
        String key = "sign:" + userId + format;

        List<Long> res = stringRedisTemplate.opsForValue().bitField(key,
                BitFieldSubCommands.create()
                        //指定是无符号的get操作，取dayOfMonth个数
                        .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth))
                        //指定无符号的get操作是从0开始
                        .valueAt(0));
        if (res == null || res.isEmpty()) {
            return Result.ok(0);
        }
        Long num = res.get(0);
        if (num == null || num == 0) {
            return Result.ok(0);
        }
        int count = 0;
        while (((num & 1) != 0)) {
            count++;
            num = num >>> 1;
        }
        return Result.ok(count);
    }
}
